﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using ASPItalia.ModelVirtualCasting.Web.RiaServices;
using System.ComponentModel;
using ASPItalia.ModelVirtualCasting.Silverlight.Data;
using GalaSoft.MvvmLight.Messaging;
using GalaSoft.MvvmLight.Command;
using System.Collections;
using ASPItalia.ModelVirtualCasting.Silverlight.BackOffice.Views;
using System.Windows.Printing;
using System.Windows.Threading;
using System.Runtime.InteropServices.Automation;
using System.Reflection;
using System.IO;
using Uploader;

namespace ASPItalia.ModelVirtualCasting.Silverlight.BackOffice.ViewModels
{
  public class HomeViewModel : ViewModelBase
  {
    PrintDocument _doc;
    DataManager _data;
    public RelayCommand<IList> SelectionChangedCommand { get; private set; }
    public RelayCommand<People> ViewDetailsCommand { get; private set; }

    public HomeViewModel()
    {
      if (DesignerProperties.IsInDesignTool)
      {
      }
      else
      {
        _data = new DataManager();
      }

      SelectionChangedCommand = new RelayCommand<IList>(SelectedChanged);
      ViewDetailsCommand = new RelayCommand<People>(ViewDetails);

      Messenger.Default.Register<MessageType>(this, ManageMessage);
    }

    private void ManageMessage(MessageType messageType)
    {
      switch (messageType)
      {
        case MessageType.Load:
          LoadPeople();
          break;
        case MessageType.Print:
          Print();
          break;
        case MessageType.Export:
          Export();
          break;
        case MessageType.Save:
          Save();
          break;
        default:
          break;
      }
    }

    private ObservableCollection<People> _people = new ObservableCollection<People>();
    public ObservableCollection<People> People
    {
      get { return _people; }
      set
      {
        _people = value;
        RaisePropertyChanged("People");
      }
    }

    public void LoadPeople()
    {
      Processing = Tuple.Create<bool, string>(true, "caricamento in corso");

      _data.LoadPeople((result) =>
      {
        if (result.Error != null)
        {
          Processing = Tuple.Create<bool, string>(false, result.Error.Message);
        }
        else
        {
          Processing = Tuple.Create<bool, string>(false, "elaborazione completata");
          People = new ObservableCollection<People>(result.Entities);
        }
      });
    }

    Tuple<bool, string> _processing;
    public Tuple<bool, string> Processing
    {
      get { return _processing; }
      set
      {
        _processing = value;
        RaisePropertyChanged("Processing");

        Messenger.Default.Send<Tuple<bool, string>>(value);
      }
    }

    public void SelectedChanged(IList items)
    {
      Messenger.Default.Send<IList>(items);
    }

    public void ViewDetails(People item)
    {
      PeopleDetails p = new PeopleDetails(item);
      p.Show();
    }

    public void Print()
    {
      _doc = new PrintDocument();
      _doc.PrintPage += new EventHandler<PrintPageEventArgs>(doc_PrintPage);
      _doc.Print("documento");
    }

    void doc_PrintPage(object sender, PrintPageEventArgs e)
    {
      Size area = e.PrintableArea;

      //DataGrid _dg = new DataGrid();
      //_dg.ItemsSource = People;
      //_dg.Width = area.Width;
      //_dg.Height = area.Height * 2;

      string outData = string.Empty;
      TextBox _dg = new TextBox();

      foreach (People item in People)
      {
        outData += ASPItalia.ModelVirtualCasting.Silverlight.BackOffice.Manager.Helper.ObjectToString(item);
      }
      _dg.Text = outData;

      e.PageVisual = _dg;
    }

    public void Export()
    {
      dynamic excel = AutomationFactory.CreateObject("Excel.Application");
      excel.Visible = true;
      dynamic workbook = excel.workbooks;
      workbook.Add();
      dynamic sheet = excel.ActiveSheet;

      dynamic cell = null;

      int i = 1;
      foreach (People item in People)
      {

        Type type = item.GetType();
        PropertyInfo[] properties = type.GetProperties();
        foreach (PropertyInfo p in properties)
        {
          try
          {
            if (p.GetValue(item, null) != null)
            {
              cell = sheet.Cells[i, 1];
              cell.Value = p.Name;
              cell.ColumnWidth = 25;
              cell = sheet.Cells[i, 2];
              cell.Value = p.GetValue(item, null);
              i++;
            }
          }
          catch (Exception)
          {
          }
        }

        i++;
      }
    }

    public void Save()
    {
      if (Application.Current.HasElevatedPermissions)
      {
        string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string filename = "test.txt";
        string path = System.IO.Path.Combine(myDocuments, filename);
        string outData = string.Empty;

        foreach (People item in People)
        {
          outData += ASPItalia.ModelVirtualCasting.Silverlight.BackOffice.Manager.Helper.ObjectToString(item);
        }
        File.WriteAllText(path, outData);

        NotificationWindow tost = new NotificationWindow();
        tost.Content = new TextBlock() { Text = "Salvataggio completato" };
        tost.Height = 50;
        tost.Width = 200;
        tost.Show(2000);
      }
    }
  }
}